package com.xh.petdogexpert.sys.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xh.petdogexpert.base.BaseController;
import com.xh.petdogexpert.base.BaseException;
import com.xh.petdogexpert.base.ResponseData;
import com.xh.petdogexpert.sys.dto.Resource;
import com.xh.petdogexpert.sys.dto.Role;
import com.xh.petdogexpert.sys.service.IRoleService;
import com.xh.petdogexpert.user.dto.RoleResourceLink;

@Controller
@RequestMapping(value = "sys/")
public class RoleController extends BaseController {

	@Autowired
	IRoleService roleService;

	final static Logger logger = LoggerFactory.getLogger(RoleController.class);

	@RequestMapping(value = "role/queryRoles")
	@ResponseBody
	public ResponseData queryRoles(Role role) {

		ResponseData rData = new ResponseData();
		List<Role> roles = roleService.queryRoles(role);
		rData.setData(roles);
		return rData;
	}
	
	@RequestMapping(value = "role/getRoleResources")
	@ResponseBody
	public ResponseData getRoleResources(Role role) {

		ResponseData rData = new ResponseData();
		List<Role> roles = roleService.getRoleResources(role);
		rData.setData(roles);
		return rData;
	}
	
	@RequestMapping(value = "role/getRoleAllResources")
	@ResponseBody
	public ResponseData getRoleAllResources(Role role) throws BaseException {

		ResponseData rData = new ResponseData();
		List<Resource> resources = roleService.getRoleAllResources(role);
		rData.setData(resources);
		return rData;
	}
	
	@RequestMapping(value = "role/updateRoleResources")
	@ResponseBody
	public ResponseData updateRoleResources( String resourcesStr) throws BaseException {

		ObjectMapper objectMapper = new ObjectMapper();
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, RoleResourceLink.class);
		List<RoleResourceLink> roleResourceLinks;
		
		try {
			roleResourceLinks = objectMapper.readValue(resourcesStr, javaType);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("转换出错");
		}
		
		roleService.updateRoleResources(roleResourceLinks);
		ResponseData rData = new ResponseData();

		rData.setData("保存成功");
		return rData;
	}
}
